package com.ruoyi.web.controller.system;


import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysClient;
import com.ruoyi.system.domain.vo.ClientRobotVo;
import com.ruoyi.system.netty.ClientWebsocketMap;
import com.ruoyi.system.service.ISysClientService;
import com.ruoyi.system.service.ISysUserService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
@Api("ws管理")
@RestController
@RequestMapping("/system/ws")
public class WebsocketController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysClientService clientService;
    @ApiOperation("测试")
    @PostMapping("/test")
    public void test(@RequestParam("msg") String msg){

        ConcurrentHashMap<String, Channel> clientChannel = ClientWebsocketMap.CLIENT_CHANNEL;

        Channel channel = clientChannel.get(msg);
        channel.writeAndFlush(new TextWebSocketFrame("1111111111111111"));
        channel.flush();
    }

    @ApiOperation("发送消息")
    @PostMapping("/sendMsg")
    public AjaxResult sendMsg(@RequestBody ClientRobotVo vo, HttpServletRequest request){

        ConcurrentHashMap<String, Channel> clientChannel = ClientWebsocketMap.CLIENT_CHANNEL;

        if(clientChannel.containsKey(vo.getCid())) {
            Channel channel = clientChannel.get(vo.getCid());
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(vo)));
            channel.flush();
            return success("操作成功");
        }else {
            return error(String.format("用户:%s，为离线状态，发送失败。",vo.getCid()));
        }
    }
}
